package com.cfweb.resouce;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import javax.ws.rs.core.Application;

import com.cfweb.api.ApplicationApi;
import com.cfweb.api.ServiceApi;
import com.cfweb.util.JsonUtil;

public class BuildResourceUtil {

	private static final String HEX_CHARS = "0123456789ABCDEF";

	private static String bytesToHex(byte[] bytes) {
		if (bytes == null) {
			return null;
		}
		final StringBuilder hex = new StringBuilder(2 * bytes.length);
		for (final byte b : bytes) {
			hex.append(HEX_CHARS.charAt((b & 0xF0) >> 4)).append(
					HEX_CHARS.charAt((b & 0x0F)));
		}
		return hex.toString();
	}

	private static String getShaText(ZipFile zip, ZipEntry entity) {
		try {
			if (entity.isDirectory()) {
				return "0";
			}
			InputStream inputStream = zip.getInputStream(entity);
			try {
				try {
					MessageDigest digest = MessageDigest.getInstance("SHA");
					byte[] buffer = new byte[4096];
					int bytesRead = -1;
					while ((bytesRead = inputStream.read(buffer)) != -1) {
						if (digest != null) {
							digest.update(buffer, 0, bytesRead);
						}
					}
					return bytesToHex(digest.digest());
				} catch (Exception e) {
					throw new IllegalStateException(e);
				}

			} finally {
				inputStream.close();
			}
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}

	public static String getResources(ZipFile zip) throws ZipException, IOException{
		List<CloudResource> resources=new ArrayList<CloudResource>();
		Enumeration<? extends ZipEntry> zipEntries=zip.entries();
		while (zipEntries.hasMoreElements()) {
	       ZipEntry entity=zipEntries.nextElement();
	       resources.add(new CloudResource(entity.getName(),entity.getSize(),getShaText(zip,entity)));
	    }
		return JsonUtil.convertToJson(resources);
	}
	
	  public static void main(String[] args) throws Exception{
		 /* File file=new File("/home/yufangjiang/Downloads/tmpp.zip");
		  String res=getResources(new ZipFile(file));
		  String contetn=ApplicationApi.resource_match(res, null);
		  System.out.println(contetn);*/
		  String contetn=ServiceApi.getParticularServiceUUID("jsb", null);
		  System.out.println(contetn);
	  }
	 
}
